import React from 'react'
import {Button,Card,Table,Modal,message} from 'antd'
import AddForm from './component/AddForm'
import AuthForm from './component/AuthForm'
import {reqRoles, reqAddRole, reqUpdateRole} from '@api/role'
import {PAGE_SIZE} from '@/utils/constant'
import  formateDate  from '@/utils/dateFormat'
import { getUsername } from '@/utils/cookies'

export default class role extends React.Component {

    AddForm = React.createRef()
    AuthForm = React.createRef()

    state = {
        roles: [], // 所有角色的列表
        role: {}, // 选中的role
        isShowAdd: false, // 是否显示添加界面
        isShowAuth: false, // 是否显示设置权限界面
    }
    initColumns=()=>{
        this.columns=[
            {title: '角色名称',dataIndex: 'name'},
            {title: '创建时间',dataIndex: 'create_time',render:formateDate},
            {title: '授权时间',dataIndex: 'auth_time',render:formateDate},
            {title: '授权人', dataIndex: 'auth_name'}
        ]
    }
    
    UNSAFE_componentWillMount(){
        this.initColumns()
    }
    componentDidMount () {
        this.getRoles()
    }
    // 初始化角色数据
    getRoles=async ()=>{
        const result = await reqRoles()
        if(result.status===0){
            const roles = result.data
            this.setState({roles})
        }
    }
    addRole=async ()=>{
        // 隐藏确认框
        this.setState({isShowAdd:false})
        
        const result = await reqAddRole(this.AddForm.current.state.roleName)
        
        if(result.status===0){
            const role = result.data
            // 在原有状态更新roles状态 避免了再发一次请求
            this.setState(state=>({
                roles:[...state.roles,role]
            }))
            message.success('添加角色成功')
        }else{
            message.error('添加角色失败')
        }
        // 获取AddForm子组件对象并重置
        this.setAddForm.current.resetFields()
    }

    updateRole=async ()=>{
        // 隐藏确认框
        this.setState({
            isShowAuth: false
        })
        const role = this.state.role
        // 把父组件的role某个值设置为子组件的某个值
        role.menus = this.AuthForm.current.state.checkedKeys
        role.auth_time = Date.now()
        role.auth_name = getUsername()
        const result = await reqUpdateRole(role)
        if(result.status == 0 ){
            message.success('权限设置成功')
        }else{
            message.error('权限设置失败')
        }
    }

    render() {
        const {roles,isShowAdd,role,isShowAuth} = this.state
        const rowSelection = {
            type:'radio',
            onChange: (selectedRowKeys, selectedRows) => {
              this.setState({role:selectedRows[0]})
            },
            selectedRowKeys:[role._id],
            onSelect:(record)=>{
                console.log(record);
                this.setState({role:record})
            }
        }

        const title =(
            <span>
                <Button type='primary' onClick={() => this.setState({isShowAdd: true})}>创建角色</Button>&nbsp;&nbsp;&nbsp;&nbsp;
                <Button type='primary' disabled={!role._id} onClick={() => this.setState({isShowAuth: true})}>设置角色权限</Button>
            </span>
        )
        return (
          <Card title={title}>
              <Table rowKey={record => record._id} rowSelection={rowSelection} dataSource={roles} columns={this.columns} pagination={{defaultPageSize:PAGE_SIZE}} onRow={record =>({ onClick:()=>{this.setState({role:record})}})} bordered/>
              <Modal title="添加角色" visible={isShowAdd} onOk={this.addRole} onCancel={()=>{this.setState({isShowAdd:false});this.setAddForm.current.resetFields()}} okText="确认"  cancelText="取消">
                <AddForm ref={this.AddForm} setAddForm={setAddForm=>this.setAddForm=setAddForm}/>
              </Modal>
              <Modal title="设置角色权限" visible={isShowAuth} onOk={this.updateRole}  onCancel={()=>{this.setState({isShowAuth:false})}} okText="确认"  cancelText="取消">
                <AuthForm ref={this.AuthForm} role={role}/>
              </Modal>
          </Card>
          
        )
    }
}
